import cv2
import os
import random
import matplotlib.pyplot as plt
def display_image(path):
    filelist = os.listdir(path)
    image = []
    for i in range(10):
        t = random.randint(0,len(filelist)-1)
        image.append(path+'/'+filelist[t])
    # i =1
    # for image_path in image:
    #     plt.subplot(2,5,i)
    #     img = cv2.imread(image_path)
    #     plt.imshow(img)
    #     plt.axis('off')
    #     i = i+1
    # plt.show()
SRC_PATH = './Resources/data/'
filelist = os.listdir(SRC_PATH)
print('{}文件夹下共有{}个文件'.format(SRC_PATH,len(filelist)))
display_image(SRC_PATH)
DST1_PATH = './Resources/resized_data'
if not os.path.exists(DST1_PATH):
    os.makedirs(DST1_PATH)
DST2_PATH = './Resources/fliped_data'
if not os.path.exists(DST2_PATH):
    os.makedirs(DST2_PATH)
#
def rdnsize(image,width,height):
    h,w,d = image.shape
    if h< height or w<width:
        dst = cv2.resize(image,(width,height))
    else:
        y = random.randint(0,h-height)
        x = random.randint(0,w-width)
        dst = image[y:y+height,x:x+width,:]
    return dst
for cnt,ff in enumerate(filelist):
    path_filename = os.path.join(SRC_PATH,ff)
    image = cv2.imread(path_filename)
    if image is None:
        print('Faild to read image:',path_filename)
        continue
    dst = rdnsize(image,224,224)
    filename = '{}_{:0>3d}.jpg'.format('resize',cnt)
    resized = os.path.join(DST1_PATH,filename)
    cv2.imwrite(resized,dst)
print('{}文件夹下共有{}个文件'.format(DST1_PATH,cnt+1))
display_image(DST1_PATH)

def rdnflip(image):
    flipcode = random.randint(-1,1)
    dst = cv2.flip(image,flipcode)
    return dst
for cnt,ff in enumerate(filelist):
    path_filename = os.path.join(SRC_PATH,ff)
    image = cv2.imread(path_filename)
    if image is None:
        print('Faild to read image:',path_filename)
        continue
    dst = rdnflip(image)
    filename = '{}_{:0>3d}.jpg'.format('flip',cnt)
    fliped = os.path.join(DST2_PATH,filename)
    cv2.imwrite(fliped,dst)
print('{}文件夹下共有{}个文件'.format(DST2_PATH,cnt+1))
display_image(DST2_PATH)